package com.miniapp.core.utils;


import com.miniapp.common.core.domain.AjaxResult;
import com.miniapp.common.core.domain.entity.miniapp.MiniAppUser;
import com.miniapp.common.enums.DeleteFlag;
import com.miniapp.common.enums.PaicFtiPolicyStatus;
import com.miniapp.common.enums.StopFlag;
import com.miniapp.common.gen.domain.*;
import com.miniapp.common.gen.mapper.*;
import com.miniapp.common.utils.DateUtils;
import com.miniapp.common.utils.StringUtils;
import com.miniapp.core.domain.paicfti.*;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 平安货运险投保参数验证
 */
@Component
public class PaicFtiParamUtils {

    private static final String CHINESE_REGEX = "[\\u4e00-\\u9fa5]"; // 定义匹配中文的正则表达式

    @Autowired
    private PaicFtiPolicyMapper paicFtiPolicyMapper;

    @Autowired
    private PaicFtiAgentMapper paicFtiAgentMapper;

    /**
     * 验证投保参数
     * @param paicFtiInsureParam
     * @return
     */
    public AjaxResult paramVerification(PaicFtiInsureParam paicFtiInsureParam){
        //0、验证是否有出单权限
        String agentPhone = paicFtiInsureParam.getLoginUser().getMiniAppUser().getPurePhoneNumber();
        AjaxResult ajaxResult = phoneAuth(agentPhone);
        if(ajaxResult.isError()){
            return ajaxResult;
        }

        //1、产品方案验证
        ajaxResult = this.productTypeVerification(paicFtiInsureParam);
        if(ajaxResult.isError()){
            return ajaxResult;
        }
        //2、验证被保人信息
        PaicFtiInsurantParam paicFtiInsurant = paicFtiInsureParam.getPaicFtiInsurant();
        ajaxResult = verifyPaicFtiInsurant(paicFtiInsurant);
        if(ajaxResult.isError()){
            return ajaxResult;
        }
        //3、货物信息验证
        ajaxResult = verifyPaicFtiCargo(paicFtiInsureParam);
        if(ajaxResult.isError()){
            return ajaxResult;
        }
        //4、验证运输信息
        ajaxResult = verifyInputPaicFtiTransport(paicFtiInsureParam.getPaicFtiTransport());
        if(ajaxResult.isError()){
            return ajaxResult;
        }
        //5、验证保险信息
        ajaxResult = verifyPaicFtiInsurance(paicFtiInsureParam);
        if(ajaxResult.isError()){
            return ajaxResult;
        }
        return AjaxResult.success();
    }

    @Autowired
    private TMiniAgentMapper tMiniAgentMapper;

    /**
     * 验证手机号是否有出单权限
     * @param phone
     * @return
     */
    public AjaxResult phoneAuth(String phone){
        if(StringUtils.isBlank(phone)){
            return AjaxResult.error("请先绑定手机号");
        }
        TMiniAgentExample tMiniAgentExample = new TMiniAgentExample();
        tMiniAgentExample.createCriteria()
                .andAgentPhoneEqualTo(phone)
                .andDelFlagEqualTo(DeleteFlag.NO_DELETED.getCode())
                .andStopFlagEqualTo(StopFlag.NO_DISABLE.getCode());
        List<TMiniAgent> tMiniAgentList = tMiniAgentMapper.selectByExample(tMiniAgentExample);
        if(CollectionUtils.isEmpty(tMiniAgentList)){
            return AjaxResult.error("抱歉，您没有出单权限");
        }else {
            return AjaxResult.success();
        }
    }


    /**
     * 产品方案验证
     * @param paicFtiInsureParam
     * @return
     */
    public AjaxResult productTypeVerification(PaicFtiInsureParam paicFtiInsureParam){
        String productType = paicFtiInsureParam.getProductType();
        if(StringUtils.isBlank(productType)){
            return AjaxResult.error("产品方案不能为空");
        }
        return AjaxResult.success();
    }

    /**
     * 验证被保人信息
     * @return
     */
    public AjaxResult verifyPaicFtiInsurant(PaicFtiInsurantParam paicFtiInsurant){
        String customerType = paicFtiInsurant.getCustomerType();
        String customerName = paicFtiInsurant.getCustomerName();
        String customerIdNum = paicFtiInsurant.getCustomerIdNum();
        String contactPerson = paicFtiInsurant.getContactPerson();
        String contactPonhe = paicFtiInsurant.getContactPonhe();
        String contactAddress = paicFtiInsurant.getContactAddress();
        if(StringUtils.isBlank(customerType) ||
                StringUtils.isBlank(customerName) ||
                StringUtils.isBlank(customerIdNum) ||
                StringUtils.isBlank(contactPerson) ||
                StringUtils.isBlank(contactPonhe) ||
                StringUtils.isBlank(contactAddress)){
            return AjaxResult.error("客户类型、客户姓名、客户证件号码、联系人、联系电话、联系地址，必填");
        }

        if(countChineseCharacters(contactAddress) < 6){
            return AjaxResult.error("联系地址请输入超过六个中文字符");
        }
        return AjaxResult.success();
    }

    /**
     * 货物信息验证
     * @param paicFtiInsureParam
     * @return
     */
    public AjaxResult verifyPaicFtiCargo(PaicFtiInsureParam paicFtiInsureParam ){
        PaicFtiCargo paicFtiCargo = paicFtiInsureParam.getPaicFtiCargo();
        String cargoType = paicFtiCargo.getCargoType();
        String packingType = paicFtiCargo.getPackingType();
        String cargoMessage = paicFtiCargo.getCargoMessage();
        if(StringUtils.isBlank(cargoType)||
                StringUtils.isBlank(packingType)||
                StringUtils.isBlank(cargoMessage)){
            return AjaxResult.error("货物类型、包装方式、货物标的描述及数量必填");
        }
        return AjaxResult.success();

    }




    /**
     * 验证运输信息
     * @param paicFtiTransport
     * @return
     */
    public AjaxResult verifyInputPaicFtiTransport(PaicFtiTransport paicFtiTransport){
        String invoiceNumber = paicFtiTransport.getInvoiceNumber();
        String waybillNumber = paicFtiTransport.getWaybillNumber();
        if(StringUtils.isBlank(invoiceNumber) && StringUtils.isBlank(waybillNumber)){
            return AjaxResult.error("‘发票号码’、‘提/运单号’，必填一个");
        }
        if(StringUtils.isNotBlank(invoiceNumber)){
            PaicFtiPolicyExample paicFtiPolicyExample = new PaicFtiPolicyExample();
            paicFtiPolicyExample.createCriteria()
                    .andInvoiceNumberEqualTo(invoiceNumber)
                    .andPolicyStatusEqualTo(PaicFtiPolicyStatus.SUCCESSFUL_INSURANCE.getCode());
            List<PaicFtiPolicy> paicFtiPolicyList = paicFtiPolicyMapper.selectByExample(paicFtiPolicyExample);
            if(CollectionUtils.isNotEmpty(paicFtiPolicyList)){
                return AjaxResult.error("发票号码:"+invoiceNumber+",不能重复投保");
            }
        }
        if(StringUtils.isNotBlank(waybillNumber)){
            PaicFtiPolicyExample paicFtiPolicyExample = new PaicFtiPolicyExample();
            paicFtiPolicyExample.createCriteria().andWaybillNumberEqualTo(waybillNumber)
                    .andPolicyStatusEqualTo(PaicFtiPolicyStatus.SUCCESSFUL_INSURANCE.getCode());
            List<PaicFtiPolicy> paicFtiPolicyList = paicFtiPolicyMapper.selectByExample(paicFtiPolicyExample);
            if(CollectionUtils.isNotEmpty(paicFtiPolicyList)) {
                return AjaxResult.error("提/运单号:" + invoiceNumber + ",不能重复投保");
            }
        }


        String licensePlateNumber = paicFtiTransport.getLicensePlateNumber();
        String placeOfDispatch = paicFtiTransport.getPlaceOfDispatch();
        String destination = paicFtiTransport.getDestination();
        String shippingTime = paicFtiTransport.getShippingTime();
        if(StringUtils.isBlank(licensePlateNumber) ||
                StringUtils.isBlank(placeOfDispatch) ||
                StringUtils.isBlank(destination) ||
                StringUtils.isBlank(shippingTime)){
            return AjaxResult.error("‘车牌号’、‘起运地描述’、‘目的地描述’、‘起运时间’必填");
        }
        return AjaxResult.success();
    }


    /**
     * 验证保险信息
     * @param paicFtiInsureParam
     * @return
     */
    public AjaxResult verifyPaicFtiInsurance(PaicFtiInsureParam paicFtiInsureParam){
        PaicFtiInsurance paicFtiInsurance = paicFtiInsureParam.getPaicFtiInsurance();
        Integer insuranceAmount = paicFtiInsurance.getInsuranceAmount();
        if(insuranceAmount == null){
            return AjaxResult.error("保险金额必填");
        }
        return AjaxResult.success();
    }



    public static int countChineseCharacters(String input) {
        // 创建Pattern对象
        Pattern pattern = Pattern.compile(CHINESE_REGEX);
        // 创建Matcher对象
        Matcher matcher = pattern.matcher(input);
        // 初始化计数器
        int count = 0;
        // 查找所有匹配项并计数
        while (matcher.find()) {
            count++;
        }
        // 返回中文字符数量
        return count;
    }

    /**
     * 投保参数入库
     * @param paicFtiInsureParam
     */
    public PaicFtiPolicy insterParam(PaicFtiInsureParam paicFtiInsureParam){
        //保单信息入库
        PaicFtiPolicy paicFtiPolicy = insertPolicy(paicFtiInsureParam);
        //插入被保人信息
        insertInsurant(paicFtiInsureParam,paicFtiPolicy);
        return paicFtiPolicy;
    }

    /**
     * 保单信息入库
     * @param paicFtiInsureParam
     */
    public PaicFtiPolicy insertPolicy(PaicFtiInsureParam paicFtiInsureParam){
        String uniqueId = paicFtiInsureParam.getUniqueId();
        //产品方案
        String productType = paicFtiInsureParam.getProductType();
        //货物信息
        PaicFtiCargo paicFtiCargo = paicFtiInsureParam.getPaicFtiCargo();
        //运输信息
        PaicFtiTransport paicFtiTransport = paicFtiInsureParam.getPaicFtiTransport();
        //保险信息
        PaicFtiInsurance paicFtiInsurance = paicFtiInsureParam.getPaicFtiInsurance();
        MiniAppUser miniAppUser = paicFtiInsureParam.getLoginUser().getMiniAppUser();
        String openId = miniAppUser.getOpenId();
        String purePhoneNumber = miniAppUser.getPurePhoneNumber();


        PaicFtiPolicy paicFtiPolicy = new PaicFtiPolicy();
        paicFtiPolicy.setUniqueId(uniqueId);
        paicFtiPolicy.setProductType(productType);
        //货物类型
        paicFtiPolicy.setCargoType(paicFtiCargo.getCargoType());
        //包装方式
        paicFtiPolicy.setPackingType(paicFtiCargo.getPackingType());
        //货物标的描述及数量
        paicFtiPolicy.setCargoMessage(paicFtiCargo.getCargoMessage());
        //发票号码
        paicFtiPolicy.setInvoiceNumber(paicFtiTransport.getInvoiceNumber());
        //提/运单号
        paicFtiPolicy.setWaybillNumber(paicFtiTransport.getWaybillNumber());
        //车牌号
        paicFtiPolicy.setLicensePlateNumber(paicFtiTransport.getLicensePlateNumber());
        //起运地
        paicFtiPolicy.setPlaceOfDispatch(paicFtiTransport.getPlaceOfDispatch());
        //目的地
        paicFtiPolicy.setDestination(paicFtiTransport.getDestination());
        //起运时间
        String shippingTime = paicFtiTransport.getShippingTime();
        Date shippingTimeData = DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH, shippingTime);
        paicFtiPolicy.setShippingTime(shippingTimeData);
        paicFtiPolicy.setInsuranceAmount(paicFtiInsurance.getInsuranceAmount());
        paicFtiPolicy.setPremium(paicFtiInsurance.getPremium());
        paicFtiPolicy.setAccoutn(paicFtiInsureParam.getAccount());
        paicFtiPolicy.setCreateTime(new Date());
        paicFtiPolicy.setAgentPhone(purePhoneNumber);
        paicFtiPolicy.setOpenId(openId);
        paicFtiPolicy.setPolicyStatus(PaicFtiPolicyStatus.UNDER_INSURANCE.getCode());

        //产品费率
        PaicFtiRateExample paicFtiRateExample = new PaicFtiRateExample();
        paicFtiRateExample.createCriteria().andProductTypeEqualTo(productType);
        List<PaicFtiRate> paicFtiRateList = paicFtiRateMapper.selectByExample(paicFtiRateExample);
        if(CollectionUtils.isNotEmpty(paicFtiRateList)){
            PaicFtiRate paicFtiRate = paicFtiRateList.get(0);
            paicFtiPolicy.setRate(paicFtiRate.getRate());
        }
        paicFtiPolicyMapper.insertSelective(paicFtiPolicy);
        return paicFtiPolicy;
    }

    @Autowired
    private PaicFtiRateMapper paicFtiRateMapper;
    @Autowired
    private PaicFtiInsurantMapper paicFtiInsurantMapper;
    /**
     * 插入被保人信息
     * @param paicFtiInsureParam
     */
    public void insertInsurant(PaicFtiInsureParam paicFtiInsureParam,PaicFtiPolicy paicFtiPolicy){
        PaicFtiInsurantParam paicFtiInsurantParam = paicFtiInsureParam.getPaicFtiInsurant();
        PaicFtiInsurant paicFtiInsurant = new PaicFtiInsurant();
        paicFtiInsurant.setPaicFtiPolicyId(paicFtiPolicy.getId());
        //客户类型：001团体、002个人
        paicFtiInsurant.setCustomerType(paicFtiInsurantParam.getCustomerType());
        paicFtiInsurant.setCustomerName(paicFtiInsurantParam.getCustomerName());
        paicFtiInsurant.setCustomerIdNum(paicFtiInsurantParam.getCustomerIdNum());
        paicFtiInsurant.setContactPerson(paicFtiInsurantParam.getContactPerson());
        paicFtiInsurant.setContactPonhe(paicFtiInsurantParam.getContactPonhe());
        paicFtiInsurant.setContactAddress(paicFtiInsurantParam.getContactAddress());
        paicFtiInsurant.setCreateTime(new Date());
        paicFtiInsurantMapper.insertSelective(paicFtiInsurant);
    }


}















